/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.zjdt.epserver.servlet.driver;

import com.zjdt.epserver.db.service4mysql.DriverServiceImpl;
import com.zjdt.epserver.db.service4mysql.TruckServiceImpl;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileExistsException;
import org.dusin.util.TheUtil;
import org.dusin.web.util.JsonUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author dusin
 */
@WebServlet(name = "UpdateLicensePhoto", urlPatterns = {"/servlet/driver/UpdateLicensePhoto"})
public class UpdateLicensePhoto extends HttpServlet {
    private DriverServiceImpl driver;
    private TruckServiceImpl truck;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");
        String jsonText=null;        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure a repository (to ensure a secure temp location is used)
        
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        //System.out.println("repository:" + repository.getAbsolutePath());
        factory.setRepository(repository);
        ServletFileUpload uploadHandler = new ServletFileUpload(factory);
        uploadHandler.setHeaderEncoding("utf-8");  //可以解决中文文件名乱码问题
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        driver = (DriverServiceImpl) context.getBean("driverService");
        
        String logid = null;
        String username =null;
        String licenseNo=null;
        String dueDate=null;
        Integer siterID=null;
        try {
            FileItem uploadFileItem = null;
            List<FileItem> items = uploadHandler.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    uploadFileItem = item;
                } else {
                    if ("logid".equals(item.getFieldName())) {
                        logid = item.getString();                        
                    } 
                    if("username".equals(item.getFieldName())){
                        username = item.getString();                        
                    }                    
                    
                    if("licenseNo".equals(item.getFieldName())){
                        licenseNo = item.getString();                        
                    }
                    if("dueDate".equals(item.getFieldName())){
                        dueDate = item.getString();                        
                    }                    
                }
            } 
            String docType = TheUtil.fileSuffix(uploadFileItem.getName());
            String filename = "li"+username+"."+docType;
            driver.updateLicensePhotoByUsername(username, dueDate,filename);
            
            String dataDirectoryStr = this.getServletContext().getInitParameter("DriverPhotoDir");
            File file = new File(dataDirectoryStr,filename); 
            //File file = new File(filename); 
            System.out.println(file.getAbsoluteFile().toString());
            if(file.exists()){
                file.delete();
            }
            uploadFileItem.write(file);           
            jsonText = JsonUtil.createSuccessJsonResponse("上传成功");
        }catch(DuplicateKeyException e){
            e.printStackTrace();
            jsonText = JsonUtil.createFailureJsonResponse("手机号码与数据库中已有记录重复");            
        } catch (FileExistsException e) {
            jsonText = JsonUtil.createFailureJsonResponse("文件已存在");
            e.printStackTrace();
        } catch (Throwable t) {
            jsonText = JsonUtil.createFailureJsonResponse("操作失败");
            t.printStackTrace();
        } finally {
            out.println(jsonText);
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
